package com.wangzhixuan.commons.shiro;

import com.wangzhixuan.commons.Constant;
import com.wangzhixuan.commons.result.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ajax shiro session超时统一处理
 * <p>
 * 参考：http://looooj.github.io/blog/2014/06/17/shiro-user-filter.html
 *
 * @author L.cm
 */
public class ShiroAjaxSessionFilter extends UserFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = WebUtils.toHttp(request);
        String xmlHttpRequest = req.getHeader("accept");
        if (StringUtils.isNotBlank(xmlHttpRequest)) {
            if (xmlHttpRequest.contains(MediaType.APPLICATION_JSON_VALUE)) {
                HttpServletResponse res = WebUtils.toHttp(response);
                // 采用res.sendError(401);在Easyui中会处理掉error，$.ajaxSetup中监听不到
                res.setHeader("oauthstatus", "401");
                // CORS "pre-flight" request
                res.setHeader("Access-Control-Allow-Origin", "*");
                res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                res.setHeader("Access-Control-Allow-Headers", "x-requested-with, Origin, X-Token, Content-Type, Accept");
                //30 min
                res.setHeader("Access-Control-Max-Age", "1800");
                Result<String> result = new Result<>();
                result.setCode(5);
                result.setSuccess(false);
                result.setMsg("未登录");
                response.getOutputStream().write(Constant.staticObjectMapper.writeValueAsBytes(result));
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                response.getOutputStream().flush();
                response.getOutputStream().close();
                return false;
            }
        }
        return super.onAccessDenied(request, response);
    }

    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        if (WebUtils.toHttp(request).getMethod().equalsIgnoreCase(RequestMethod.OPTIONS.name())) {
            //跨域请求允许访问
            return true;
        }
        return super.onPreHandle(request, response, mappedValue);
    }

}